import React, { Component } from 'react'
import Head from '../component/Head';
import Footer from '../component/Footer';
import List from '../component/List';

export default class Car extends Component {
    constructor(props){
        super(props);
        this.state={
            totalNum:0,
            totalPrice:0,
            checkAll:false,
            list:[{id:1,name:"React入门",num:1,price:59,checked:false},{id:2,name:"React进阶",num:2,price:69,checked:false},{id:3,name:"React入狱",num:3,price:99,checked:false}]
        }
    }
    calc=(item,n)=>{
        this.setState({
            list:this.state.list.map(info=>{
                if(item==info){
                    info.num=info.num+n;
                }
                return info;
            })
        },()=>{
            this.total();
        })
    }
    del=(id)=>{
        this.setState({
            list:this.state.list.filter(item=>item.id!=id)
        },()=>{
            this.total();
            if(this.state.list.length==0){
                this.setState({
                    checkAll:false
                })
            }
        })
    }
    setcheckAll=(flag)=>{
        this.setState({
            checkAll:flag,
            list:this.state.list.map(item=>{
                item.checked=flag;
                return item;
            })
        },()=>{
            this.total();
        })
    }
    checkonebtn=(flag,item)=>{
        this.setState({
            list:this.state.list.map(info=>{
                if(info==item){
                    info.checked=flag; 
                }
                return info;
            })
        },()=>{
            this.setState({
                checkAll:this.state.list.every(item=>item.checked)
            })
            this.total();
        })
    }
    total(){
        let num=0;
        let price=0;
        let res=this.state.list.filter(item=>item.checked);
        if(res.length){
            num=res.map(item=>item.num).reduce((a,b)=>a+b);
            price=res.map(item=>item.num*item.price).reduce((a,b)=>a+b);
        }

        this.setState({
            totalNum:num,
            totalPrice:price
        })
        
    }
  render() {
    return (
      <div>
          <h3>购物车2.0</h3>
          <div className="table">
                <Head checkAll={this.state.checkAll} setcheckAll={this.setcheckAll}></Head>
               <List list={this.state.list} calc={this.calc} del={this.del} checkonebtn={this.checkonebtn}></List>
               <Footer totalNum={this.state.totalNum} totalPrice={this.state.totalPrice} ></Footer>
                
          </div>
      </div>
    )
  }
}
